package hashDemo;

/**
 * @author Ajie
 * @date 2022/6/23
 * @function
 */
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 原文链接：https://blog.csdn.net/weixin_43944305/article/details/122122484
 * @param <K>
 * @param <V>
 *     自定义移出最老的元素。
 *     removeEldestEntry
 *
 * get方法将元素放置队尾原因
 *
 * public V get(Object key) {
 *         Node<K,V> e;
 *         if ((e = getNode(hash(key), key)) == null)
 *             return null;
 *         if (accessOrder) //accessOrder;
 *             afterNodeAccess(e);
 *         return e.value;
 *     }
 *
 */
public class LruCacheLinkedHashMap<K,V> extends LinkedHashMap<K,V> {

    private final int maxCapacity;//最大上限
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public LruCacheLinkedHashMap(int maxCapacity) {
        super(maxCapacity, DEFAULT_LOAD_FACTOR, true);
        this.maxCapacity = maxCapacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        // 当达到预设缓存上限时删除最老元素
        return this.size() > maxCapacity;
    }

    public static void main(String[] args) {
        LruCacheLinkedHashMap<String, Object> map = new LruCacheLinkedHashMap<>(4);

        map.put("1","1");
        map.put("13","13");
        map.put("12","12");
        map.put("10","10");
        map.put("15","15");

        System.out.println("LruLinkedHashMap:main:"+map);
        printMap(map);

        map.get("12");

        System.out.println("LruCacheLinkedHashMap:main:get 12----->");
        printMap(map);
    }

    private static void printMap(LruCacheLinkedHashMap<String, Object> map) {
        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> next = iterator.next();
            System.out.println("LruLinkedHashMap:main:key:"+next.getKey()+" v:"+next.getValue());
        }
    }

}